<?php
namespace app\api\service;

use app\BaseService;
use think\exception\ValidateException;
use think\facade\Db;
use app\api\model\User as UserModel;
use app\api\model\UserToken as UserTokenModel;
use app\api\model\UserTemp as UserTempModel;
use app\api\model\UserLinePrice as UserLinePriceModel;
use utils\wechart\WxuserService;

class UserService extends BaseService 
{
    //登录或者临时注册
    public function loginOrtempRegister($res) 
    {
        $where = [
            'openid' => $res['openid']
        ];
        $info = UserModel::where($where)->field('id,nickname,avatar,type,mobile,openid')->find();
        //如果不存在，表示新用户
        if (!$info) {
            $tempUserId = UserTempModel::where('openid' , $res['openid'])->value('id');
            if (!$tempUserId) {
                $insert = [
                    'openid' => $res['openid'],
                    'fleet_id' => $res['fid'],
                    'content' => json_encode($res, JSON_UNESCAPED_UNICODE),
                    'create_time' => time()
                ];
                $userRes = UserTempModel::create($insert);
                $tempUserId = $userRes->id;
            }
            $userInfo = [
                'temp_user_id' => $tempUserId,
                'user_id' => 0,
                'openid' =>  $res['openid'],
                'bindMobile' => 1, //是否绑定手机号， 1表示绑定, 0表示无需绑定
                'type'  => 0,
                'nickname' => '',
                'avatar' => '',
                'token' => '',
                'mobile' => '',
                'expire' => '',
            ];
        } else { //老用户
            //如果是老用户，但是没有填写手机号， 需要绑定手机号
            if ($info['mobile']) { 
                $loginRes = $this->loginFn($info);
                $token= $loginRes['token'];
                $expire = $loginRes['expire'];
                $userInfo = [
                    'temp_user_id' => 0,
                    'user_id' => $info['id'],
                    'nickname' => $res['nickName'],
                    'avatar' => $res['avatarUrl'],
                    'openid' => $info['openid'],
                    'type'  => $info['type'],
                    'token' => $token,
                    'expire' => $expire,
                    'mobile' => $info['mobile'],
                    'bindMobile' => 0, //不绑定手机号
                ];
                cache('user_token'.$token, $userInfo ,['expire' => $expire]);
            } else {
                $userInfo = [
                    'temp_user_id' => 0,
                    'user_id' => $info['id'],
                    'openid' =>  $res['openid'],
                    'bindMobile' => 1, //是否绑定手机号， 1表示绑定, 0表示无需绑定
                    'type'  => $info['type'],
                    'nickname' => '',
                    'avatar' => '',
                    'token' => '',
                    'mobile' => '',
                    'expire' => '',
                ];
            }
        }
        return $userInfo;
    }

    //注册且绑定手机
    public function registerAndBindMobile($openid, $res) 
    {
        //openid 验证用户是否存在
        $info = UserModel::where('openid' , $openid)->find();
        if ($info) { //老用户
            if (!$info['mobile']){  
                $update = [
                    'mobile' => $res['phoneNumber']
                ];
                $id = UserModel::where('openid' , $openid)->update($update);
                if (!$id) {
                    throw new ValidateException ('用户手机绑定失败');
                }
            }
        } else { //新用户
            $userTemp = UserTempModel::where('openid', $openid)->find();
            if (!$userTemp) {
                throw new ValidateException ('用户临时信息不存在');
            }
            $wxUser = json_decode($userTemp['content'], true);
            //验证是否是导入的用户
            $where = [
                'mobile' => $res['phoneNumber']
            ];
            $info = UserModel::where($where)->find();
            //绑定的手机号也不存在，表示是新用户
            if (!$info) {
                $insert = [
                    'openid' => $wxUser['openid'],
                    'unionid' => !empty($wxUser['unionId'])?$wxUser['unionId']:'',
                    'type' => 0,
                    'nickname' => $wxUser['nickName'],
                    'avatar' => $wxUser['avatarUrl'],
                    'gender' => $wxUser['gender'],
                    'mobile' => $res['phoneNumber'],
                    'language' => $wxUser['language'],
                    'country' => $wxUser['country'],
                    'province' => $wxUser['province'],
                    'city' => $wxUser['city'],
                    'create_time' => time(),
                ];
                $userRes = UserModel::create($insert);
                if (!$userRes) {
                    throw new ValidateException ('注册失败');
                }
                $insert['id'] = $userRes->id;
                $info = $insert;
            } else {
                //绑定的手机号已经存在，表示是导入用户，只更新用户的微信信息
                $update = [
                    'openid' => $wxUser['openid'],
                    'unionid' => !empty($wxUser['unionId'])?$wxUser['unionId']:'',
                    'nickname' => $wxUser['nickName'],
                    'avatar' => $wxUser['avatarUrl'],
                    'gender' => $wxUser['gender'],
                    'language' => $wxUser['language'],
                    'country' => $wxUser['country'],
                    'province' => $wxUser['province'],
                    'city' => $wxUser['city'],
                ];
                $userRes = UserModel::where('id', $info['id'])->update($update);
                if (!$userRes) {
                    throw new ValidateException ('注册失败');
                }
                $info = $info->toArray();
                $info = array_merge($info, $update);
            }
            if ($userTemp->fleet_id > 0) {
                Db::name('user_fleet')->insert(['user_id' => $userRes->id, 'fleet_id' => $userTemp->fleet_id]);
            }
            UserTempModel::where('openid' , $wxUser['openid'])->delete();
        }
        $loginRes = $this->loginFn($info);
        $token  = $loginRes['token'];
        $expire = $loginRes['expire'];
        $userInfo = [
            'temp_user_id' => 0,
            'user_id' => $info['id'],
            'nickname' => $info['nickname'],
            'type'  => $info['type'],
            'avatar' => $info['avatar'],
            'openid' => $info['openid'],
            'token' => $token,
            'expire' => $expire,
            'mobile' => $info['mobile'],
            'bindMobile' => 1, //不绑定手机号
        ];
        cache('user_token'.$token, $userInfo ,['expire' => $expire]);
        return $userInfo;
    }

    public function loginFn($info) 
    {
        $checkWhere = [
            'user_id' => $info['id']
        ];
        $userToken = UserTokenModel::where($checkWhere)->find();
        $token = getToken($info['id']);
        $expire = 30 * 86400 + time();
        if (!$userToken) { 
            $insert = [
                'token' => $token,
                'openid' => $info['openid'],
                'user_id' => $info['id'],
                'expire' => $expire,
                'create_time' => time()
            ];
            $userTokenRes  = UserTokenModel::create($insert);
            if (!$userTokenRes) {
                throw new ValidateException ('登录失败');
            }
        } else {
            $update = [
                'token' => $token,
                'expire' => $expire,
                'last_update_time' => time()
            ];
            $userTokenRes  = UserTokenModel::where($checkWhere)->update($update);
            if (!$userTokenRes) {
                throw new ValidateException ('登录失败');
            }
        }
        return ['expire' => $expire, 'token' => $token];
    }

    public function userLinePrice($userId, $lineId, &$price = null) 
    {
        $userLinePrice = UserLinePriceModel::where('user_id', $userId)->where('line_id', $lineId)->value('price');
        if (!empty($userLinePrice)) {
            if ($price >= 0) {
                $price = $userLinePrice;
            }
        }
    }
}